<template>
    <div class="body">
    <!-- 搜索菜单 -->
        <el-form :model="form" label-width="auto" class="search-form">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="课程名称">
            <el-input v-model="form.name" placeholder="请输入课程名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="渠道名称">
            <el-select v-model="form.region1" placeholder="课程类型" style="width: 100%">
              <el-option label="舞蹈类" value="1" />
              <el-option label="游泳类" value="2" />
              <el-option label="拳击类" value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="适用人群">
            <el-select v-model="form.region2" placeholder="适用人群" style="width: 100%">
              <el-option label="中小学生" value="1" />
              <el-option label="上班族" value="2" />
              <el-option label="小白用户" value="3" />
              <el-option label="健身达人" value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="最低价格">
            <el-input-number v-model="form.minCount" :min="0" :max="10000" :step="100" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="最高价格">
            <el-input-number v-model="form.maxCount" :min="0" :max="10000" :step="100"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="onSubmit" icon="Search" class="mr-10">搜索</el-button>
            <el-button icon="Refresh" class="mr-10"  @click="handleReset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
        </el-form>
    <!-- 功能按钮 -->
        <div class="btn-group">
      <el-button type="primary" plain icon="Plus" @click="openDialog">新增</el-button>
      <el-button type="success" plain :disabled="selectedRow.length === 0" icon="Edit" @click="handleEdit">修改</el-button>
      <el-button type="danger" plain :disabled="selectedRow.length === 0" icon="Delete" @click="handleDelete">删除</el-button>
      <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </div>
    <!-- 表格 -->
       <el-table
  :data="tableData"
  stripe
  style="width: 100%"
  @selection-change="handleSelectionChange"
>
  <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column prop="courseId" label="课程编号"/>
            <el-table-column prop="type" label="课程类型">
  <template #default="scope">
    <el-tag
      :color="typeTagColor(scope.row.type)"
      effect="plain"
      style="color: #fff;"
    >
      {{ typeFormatter(scope.row) }}
    </el-tag>
  </template>
</el-table-column>
            <el-table-column prop="name" label="课程名称" />
            <el-table-column prop="price" label="课程价格" />
            <el-table-column prop="applyTo" label="课程适用人群">
  <template #default="scope">
    <el-tag :type="applyToTagType(scope.row.applyTo)">
      {{ applyToFormatter(scope.row) }}
    </el-tag>
  </template>
</el-table-column>
            <el-table-column prop="info" label="课程简介" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column fixed="right" label="操作" min-width="120">
                <template #default>
                    <el-button link type="primary" size="small" @click="handleEdit">编辑</el-button>
                    <el-button link type="primary" size="small" @click="handleDelete">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
    </div>

    <!-- 模态框 -->
<el-dialog
  v-model="dialogVisible"
  title="添加课程"
  width="30%"
  :close-on-click-modal="false"
>
  <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="80px">
    <el-form-item label="课程名称" prop="name">
      <el-input v-model="addForm.name" placeholder="请输入课程名称" />
    </el-form-item>
    <el-form-item label="课程类型" prop="type">
      <el-select v-model="addForm.type" placeholder="请选择课程类型" style="width: 100%">
        <el-option label="舞蹈类" :value="1" />
        <el-option label="游泳类" :value="2" />
        <el-option label="拳击类" :value="3" />
      </el-select>
    </el-form-item>
    <el-form-item label="适用人群" prop="applyTo">
      <el-select v-model="addForm.applyTo" placeholder="请选择适用人群" style="width: 100%">
        <el-option label="中小学生" :value="1" />
        <el-option label="上班族" :value="2" />
        <el-option label="小白用户" :value="3" />
        <el-option label="健身达人" :value="4" />
      </el-select>
    </el-form-item>
    <el-form-item label="课程价格" prop="price">
      <el-input-number v-model="addForm.price" :min="0" style="width: 100%" />
    </el-form-item>
    <el-form-item label="课程简介" prop="info">
      <el-input v-model="addForm.info" type="textarea" placeholder="请输入课程简介" />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="dialogVisible = false">关闭</el-button>
    <el-button type="primary" @click="handleAddOrEdit">提交</el-button>
  </template>
</el-dialog>
</template>

<script setup>
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, onMounted, reactive } from 'vue'
import Cookies from 'js-cookie'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

const form = reactive({
  name: '',
  region1: '',
  region2: '',
  region3: '',
  minCount: 0,
  maxCount: 0,
})

const token = Cookies.get('Admin-Token')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表格数据
const tableData = ref([])

// 选中行
const selectedRow = ref([])

// 对话框显示状态
const dialogVisible = ref(false)
const dialogMode = ref('add') // 'add' 或 'edit'

// 新增课程表单
const addForm = reactive({
  name: '',
  type: '',
  applyTo: '',
  price: null,
  info: ''
})
const addFormRef = ref(null)
const addRules = {
  name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择课程类型', trigger: 'change' }],
  applyTo: [{ required: true, message: '请选择适用人群', trigger: 'change' }],
  price: [{ required: true, message: '请输入课程价格', trigger: 'blur' }],
  info: [{ required: true, message: '请输入课程简介', trigger: 'blur' }]
}

// 动态组装参数
const mapFormToParams = () => {
  const params = {}
  if (form.name && form.name.trim() !== '') params.name = form.name
  if (form.region1 && form.region1 !== '') params.type = form.region1 // 课程类型
  if (form.region2 && form.region2 !== '') params.applyTo = form.region2 // 适用人群
  if (form.minCount !== null && form.minCount !== undefined && form.minCount !== 0) params.minPrice = form.minCount
  if (form.maxCount !== null && form.maxCount !== undefined && form.maxCount !== 0) params.maxPrice = form.maxCount
  return params
}

// 获取表格数据
const fetchTableData = async (params = {}) => {
  try {
    const response = await axios.get(
      'http://47.104.167.34:9100/prod-api/tienchin/course/list',
      {
        params: {
          pageNum: currentPage.value,
          pageSize: pageSize.value,
          ...params
        },
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    )
    tableData.value = response.data.rows || []
    total.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('获取课程列表失败')
    console.error(error)
  }
}

// 搜索
const onSubmit = () => {
  currentPage.value = 1
  fetchTableData(mapFormToParams())
}

// 分页切换每页条数
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchTableData(mapFormToParams())
}

// 分页切换页码
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchTableData(mapFormToParams())
}

// 重置
const handleReset = () => {
  form.name = ''
  form.region1 = ''
  form.region2 = ''
  form.region3 = ''
  form.minCount = null
  form.maxCount = null
  currentPage.value = 1
  fetchTableData()
}

// 打开对话框
const openDialog = () => {
  dialogMode.value = 'add'
  Object.assign(addForm, {
    name: '',
    type: '',
    applyTo: '',
    price: null,
    info: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  const editTarget = row || selectedRow.value[0]
  if (!editTarget) {
    ElMessage.warning('请先选择要编辑的课程')
    return
  }
  dialogMode.value = 'edit'
  editingRow.value = editTarget
  Object.assign(addForm, {
    name: editTarget.name,
    type: editTarget.type,
    applyTo: editTarget.applyTo,
    price: editTarget.price,
    info: editTarget.info
  })
  dialogVisible.value = true
}

// 类型格式化
const typeFormatter = (row) => {
  switch (row.type) {
    case 1:
    case '1':
      return '舞蹈类'
    case 2:
    case '2':
      return '游泳类'
    case 3:
    case '3':
      return '拳击类'
    default:
      return row.type
  }
}

// 类型标签颜色（自定义颜色）
const typeTagColor = (type) => {
  switch (type) {
    case 1:
    case '1':
      return '#409EFF' // 蓝色
    case 2:
    case '2':
      return '#67C23A' // 绿色
    case 3:
    case '3':
      return '#909399' // 灰色
    default:
      return '#dcdfe6'
  }
}

// 适用人群格式化
const applyToFormatter = (row) => {
  switch (row.applyTo) {
    case 1:
    case '1':
      return '中小学生'
    case 2:
    case '2':
      return '上班族'
    case 3:
    case '3':
      return '小白用户'
    case 4:
    case '4':
      return '健身达人'
    default:
      return row.applyTo
  }
}

// 适用人群标签颜色
const applyToTagType = (applyTo) => {
  switch (applyTo) {
    case 1:
    case '1':
      return 'primary'
    case 2:
    case '2':
      return 'success'
    case 3:
    case '3':
      return 'info'
    case 4:
    case '4':
      return 'danger'
    default:
      return ''
  }
}

// 选中变化时触发
const handleSelectionChange = (val) => {
  selectedRow.value = val
}

// 删除课程
const handleDelete = async (row) => {
  let ids = []
  let msg = ''
  if (row && row.courseId) {
    ids = [row.courseId]
    msg = `是否确认删除课程编号为 "${row.courseId}" 的数据项？`
  } else if (selectedRow.value.length > 0) {
    ids = selectedRow.value.map(item => item.courseId)
    msg = `是否确认删除选中的 ${ids.length} 个课程（编号：${ids.join(', ')}）？`
  } else {
    ElMessage.warning('请先选择要删除的课程')
    return
  }

  try {
    await ElMessageBox.confirm(
      msg,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    for (const id of ids) {
      await axios.delete(`http://47.104.167.34:9100/prod-api/tienchin/course/${id}`, {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })
    }
    ElMessage.success('删除成功')
    fetchTableData(mapFormToParams())
    selectedRow.value = []
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
    // 用户取消时不提示
  }
}

// 导出为xlsx
const handleExport = () => {
  if (!tableData.value.length) {
    ElMessage.warning('暂无数据可导出')
    return
  }
  // 只导出当前页数据，如需全部数据请自行调整 fetchTableData
  const exportData = tableData.value.map(row => ({
    '课程编号': row.courseId,
    '课程类型': typeFormatter(row),
    '课程名称': row.name,
    '课程价格': row.price,
    '课程适用人群': applyToFormatter(row),
    '课程简介': row.info,
    '创建时间': row.createTime
  }))
  const ws = XLSX.utils.json_to_sheet(exportData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '课程列表')
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '课程列表.xlsx')
}

// 新增课程提交
const handleAddOrEdit = () => {
  addFormRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (dialogMode.value === 'add') {
        await axios.post(
          'http://47.104.167.34:9100/prod-api/tienchin/course',
          { ...addForm },
          {
            headers: {
              Authorization: `Bearer ${token}`
            }
          }
        )
        ElMessage.success('新增课程成功')
      } else if (dialogMode.value === 'edit' && editingRow.value) {
        await axios.put(
          `http://47.104.167.34:9100/prod-api/tienchin/course`,
          { ...addForm, courseId: editingRow.value.courseId },
          {
            headers: {
              Authorization: `Bearer ${token}`
            }
          }
        )
        ElMessage.success('修改课程成功')
      }
      dialogVisible.value = false
      fetchTableData(mapFormToParams())
    } catch (error) {
      ElMessage.error(dialogMode.value === 'add' ? '新增课程失败' : '修改课程失败')
      console.error(error)
    }
  })
}

onMounted(() => {
  fetchTableData()
})
</script>

<style lang="scss" scoped>
.body{
  padding: 20px;
  background: #f8f9fb;
  min-height: 100vh;
}
</style>